import {Component, OnInit} from '@angular/core';
import {MainService} from '../main.service';

@Component({
  selector: 'app-news',
  templateUrl: './news.component.html',
  styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit {
  public listOfSelection = [
    {
      text: '全选',
      onSelect: () => {
        this.checkAll(true);
      }
    },
    {
      text: '选中奇数行',
      onSelect: () => {
        this.dataSet.forEach((data, index) => data.checked = index % 2 !== 0);
        this.refreshStatus();
      }
    },
    {
      text: '选中偶数行',
      onSelect: () => {
        this.dataSet.forEach((data, index) => data.checked = index % 2 === 0);
        this.refreshStatus();
      }
    }
  ];
  public allChecked = false;
  public dataSet: Array<{
    checked: boolean;
    id: number;
    title: string;
    content: string;
    categoryname: string;
    departmentname: string;
    time: string;
  }> = [];
  private allData = [];

  // 搜索框
  public indeterminate = false;
  public inputValue: string;
  public filteredOptions = [];
  private options = [];
  // 新闻分类
  public newsType: string;
  public department: string;

  constructor(private newsService: MainService) {
    this.filteredOptions = this.options;
  }

  private getNews() {
    const data = {'x-access-token': localStorage.token};
    this.newsService.getNews(data).subscribe(res => {
      if (res['result'] === 0) {
        this.dataSet = res['data']['list'];
        this.allData = this.dataSet;
        for (let i = 0, len = this.dataSet.length; i < len; i++) {
          this.options.push(this.dataSet[i].title);
        }
      }
    });
  }

  public onInput(value: string): void {
    this.filteredOptions = this.options.filter(option => option.toLowerCase().indexOf(value.toLowerCase()) === 0);
    const filterFunc = (item) => {
      return this.inputValue.length ? item.title.toLowerCase().indexOf(this.inputValue.toLowerCase()) !== -1 : true;
    };
    const data = this.allData.filter(item => filterFunc(item));
    this.dataSet = data;
  }

  refreshStatus(): void {
    const allChecked = this.dataSet.every(value => value.checked === true);
    const allUnChecked = this.dataSet.every(value => !value.checked);
    this.allChecked = allChecked;
    this.indeterminate = (!allChecked) && (!allUnChecked);
  }

  checkAll(value: boolean): void {
    this.dataSet.forEach(data => data.checked = value);
    this.refreshStatus();
  }

  ngOnInit() {
    this.getNews();
  }

}
